package edu.xlh.travel.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import edu.xlh.travel.common.Result;
import edu.xlh.travel.dao.CarouselDao;
import edu.xlh.travel.pojo.*;
import edu.xlh.travel.pojo.querypojo.QueryCarousel;
import edu.xlh.travel.service.CarouselService;
import edu.xlh.travel.util.DateTimeUtil;
import edu.xlh.travel.util.IdWorker;
import edu.xlh.travel.util.PageResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.*;

@Service
@Transactional
public class CarouselServiceImpl implements CarouselService {
    @Autowired
    private CarouselDao carouselDao;
    @Autowired
    private IdWorker idWorker;

    @Override
    public Result findAllCarousel(int page, int limit, HttpSession session) {
        User user = (User)session.getAttribute("admin");
        if (user == null) {
            return new Result(201,"会话过期，请重新登陆");
        }
        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> carousel = new ArrayList<>();
                carousel.add(criteriaBuilder.equal(root.get("delFlag"), "0"));
                return criteriaBuilder.and(carousel.toArray(new Predicate[carousel.size()]));
            }
        };
        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");
        Pageable pageable= PageRequest.of(page-1,limit ,sort);
        Page<Carousel> carouselPage = carouselDao.findAll(specification, pageable);
        if (carouselPage!=null) {
            return new Result(0 , "轮播消息分页数据获取成功" , new PageResult<Carousel>(carouselPage.getTotalElements(), carouselPage.getContent()));
        }
        return new Result(201 , "返回轮播消息列表失败或者暂时没有轮播消息");
    }

    @Override
    public Result edit(String id, Carousel carousel, HttpSession session) {
        User user = (User)session.getAttribute("admin");
        if (user == null) {
            return new Result(201,"会话过期，请重新登陆");
        }
        carousel.setId(id);
        carousel.setModifyTime(new Date());
        try {
            carouselDao.updateCarouselByCarouselId(carousel);
        } catch (Exception e) {
            return new Result(201 , "轮播信息数据修改失败");
        }
        return new Result(200 , "轮播信息数据修改成功");
    }

    @Override
    public Result batchDelete(JSONArray jsonArray, HttpSession session) {
        List<Carousel> carouselList = JSON.parseArray(jsonArray.toJSONString() , Carousel.class);
        try {
            carouselList.stream().iterator().forEachRemaining(carousel -> {
                carouselDao.updateCarouselDelFlagByCarouselId(carousel.getId() , "1");
            });
        }catch (Exception e) {
            return new Result(201);
        }
        return new Result(200);
    }

    @Override
    public Result deleteById(String id, HashMap hashMap, HttpSession session) {
        User user = (User)session.getAttribute("admin");
        if (user == null) {
            return new Result(201,"会话过期，请重新登陆");
        }
        String carouselId = (String) hashMap.get("id");
        if (id.equals(carouselId)) {
            try {
                carouselDao.updateCarouselDelFlagByCarouselId(carouselId , "1");
            } catch (Exception e) {
                return new Result(201 , "id为"+carouselId+"的轮播信息记录"+"删除失败");
            }
        } else {
            return new Result(202 , "id为"+carouselId+"的轮播信息id有问题");
        }
        return new Result(200 , "id为"+carouselId+"的轮播信息记录"+"删除成功");
    }

    @Override
    public Result QueryCarouselByCondition(Integer page, Integer limit, QueryCarousel queryCarousel, HttpSession session) {
        User userFromSession = (User)session.getAttribute("admin");
        if (userFromSession == null) {
            return new Result(201,"会话过期，请重新登陆");
        }

        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> carouselTaskList = new ArrayList<>();
                if (StringUtils.isNotEmpty(queryCarousel.getTitle())) {
                    carouselTaskList.add(criteriaBuilder.like(root.get("title") , queryCarousel.getTitle()));
                }
                if (StringUtils.isNotEmpty(queryCarousel.getComment())) {
                    carouselTaskList.add(criteriaBuilder.like(root.get("orderId") , queryCarousel.getComment()));
                }
                if (queryCarousel.getCreateTime() != null) {
                    String crateTime = DateTimeUtil.dateToStr(queryCarousel.getCreateTime(), "yyyy-MM-dd");
                    String crateTimeStartTimeToStr = crateTime + " " + "00:00:00";
                    String crateTimeEndTimeToStr = crateTime + " " + "23:59:59";
                    Date crateTimeStartTimeToDate = DateTimeUtil.strToDate(crateTimeStartTimeToStr , "yyyy-MM-dd HH:mm:ss");
                    Date crateTimeEndTimeToDate = DateTimeUtil.strToDate(crateTimeEndTimeToStr , "yyyy-MM-dd HH:mm:ss");
                    carouselTaskList.add(criteriaBuilder.between(root.get("createTime") ,  crateTimeStartTimeToDate , crateTimeEndTimeToDate));
                }
                if (queryCarousel.getModifyTime() != null) {
                    String modifyTime = DateTimeUtil.dateToStr(queryCarousel.getModifyTime(), "yyyy-MM-dd");
                    String modifyTimeStartTimeToStr = modifyTime + " " + "00:00:00";
                    String modifyTimeEndTimeToStr = modifyTime + " " + "23:59:59";
                    Date modifyTimeStartTimeToDate = DateTimeUtil.strToDate(modifyTimeStartTimeToStr , "yyyy-MM-dd HH:mm:ss");
                    Date modifyTimeEndTimeToDate = DateTimeUtil.strToDate(modifyTimeEndTimeToStr , "yyyy-MM-dd HH:mm:ss");

                    carouselTaskList.add(criteriaBuilder.between(root.get("modifyTime") ,  modifyTimeStartTimeToDate , modifyTimeEndTimeToDate));
                }
                carouselTaskList.add(criteriaBuilder.equal(root.get("delFlag") ,"0"));
                return criteriaBuilder.and(carouselTaskList.toArray(new Predicate[carouselTaskList.size()]));
            }
        };
        Pageable pageable= PageRequest.of(page-1,limit);
        Page<Carousel> carouselListPage  = carouselDao.findAll(specification , pageable);
        if (carouselListPage!=null) {
            return new Result(0 , "轮播信息列表分页数据获取成功" , new PageResult<Carousel>(carouselListPage.getTotalElements(), carouselListPage.getContent()));
        }
        return new Result(201 , "轮播信息列表列表失败");
    }

    @Override
    public Result add(Carousel carousel, HttpSession session) {
        User user = (User)session.getAttribute("admin");
        if (user == null) {
            return new Result(201,"会话过期，请重新登陆");
        }
        carousel.setId(idWorker.nextId() + "")
                .setCreateTime(new Date())
                .setModifyTime(new Date())
                .setDelFlag("0");
        try {
            carouselDao.save(carousel);
        } catch (Exception e) {
            return new Result(201 , "轮播信息数据添加失败");
        }
        return new Result(200 , "轮播信息数据添加成功");
    }
}
